<?php

class Nimblecms_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract {
	
	private $_noAuth = array(
		'module' => 'users',
		'controller' => 'index',
		'action' => 'login'
	);
	private $_noAcl = array(
		'module' => 'users',
		'controller' => 'index',
		'action' => 'login'
	);
	
	private $_acl = null;
	
	public function __construct() {
		
		if ($this->_acl === null)
			$this->_acl = new Nimblecms_Auth_Acl ();
	}
	
	public function preDispatch(Zend_Controller_Request_Abstract $request) {
		
		$auth = Zend_Auth::getInstance ();
		
		if ($auth->hasIdentity ()) {
			
			$storage = $auth->getStorage ()->read ();
			
			$role = $storage->role;
		
		} else {
			$role = 'guest';
		}
		
		Zend_View_Helper_Navigation_HelperAbstract::setDefaultAcl($this->_acl);
                Zend_View_Helper_Navigation_HelperAbstract::setDefaultRole($role);
		
		$uri = $request->getRequestUri();
		$uri = strtolower($uri);
		
		$uri = rtrim($uri, '/') . '/';
		if (strpos($uri, '/admin/') !== false) {
			$resource = 'admin';
			
			if (!$this->_acl->has($resource)) {
				$resource = null;
			}
			
			if (! $this->_acl->isAllowed ( $role, $resource, null )) {
				$request->setControllerName ( 'auth' )->setActionName ( 'login' );
			}
		
		} else {
			$module = $request->module;
			$controller = $request->controller;
			$action = $request->action;
		
			$resource = $module . '_' . $controller;
			
			if (!$this->_acl->has($resource)) {
				$resource = null;
			}
			
			if (!$this->_acl->isAllowed($role, $resource, $action)) {
				if (!$auth->hasIdentity()) {
					$module     = $this->_noAuth['module'];
					$controller = $this->_noAuth['controller'];
					$action     = $this->_noAuth['action'];
				} else {
					$module     = $this->_noAcl['module'];
					$controller = $this->_noAcl['controller'];
					$action     = $this->_noAcl['action'];
				}
			}
			$request -> setModuleName($module)
					 -> setControllerName($controller)
					 -> setActionName($action);
		}
	}
}